<template>
  <van-dialog
    v-model.trim="activationVisible"
    title="激活码"
    show-cancel-button
    :before-close="(action, done) => done(false)"
    @cancel='closeVisble'
    @confirm='activationConfirm'>
    <van-field v-model="codeText" autofocus placeholder="请输入激活码" />
  </van-dialog>
</template>

<script>
import Vue from "vue";
import { mapState } from "vuex";
import { Dialog, Field, Toast } from "vant";
import { Encrypt } from '@/utils/secret';
import request from '@/utils/axios';
Vue.use(Dialog);
Vue.use(Field);
Vue.use(Toast);

export default {
  name: "Activation",
  props: {},
  data() {
    return {
      codeText: "",
    };
  },
  computed: {
    ...mapState({
      deviceID: 'deviceID',
      fingerprint: 'fingerprint',
      IMEI: 'IMEI'
    }),
    activationVisible: {
      get() {
        return this.$store.state.activationVisible;
      },
      set() {
        this.closeVisble();
      },
    },
  },
  methods: {
    closeVisble() {
      this.$store.commit("SET_TOTLE_DATA", {
        activationVisible: false,
      });
    },
    async activationConfirm() {
      const activeCode = this.codeText;
      if(!activeCode) {
        return;
      }
      const deviceInfo = Encrypt(`${this.fingerprint}/IMEI:${this.IMEI}`);
      const data = await request.post('/app/activate/code', {
        activeCode,
        deviceInfo,
        deviceID: this.deviceID,
      });
      if (data.code !== 0) {
        Toast({
          message: data.msg || '激活失败',
          position: 'bottom',
        });
        return;
      }
      await AutoWeb.autoPromise('setActiveCode', { activeCode });
      this.$store.commit("SET_TOTLE_DATA", { activeCode });
      await this.$store.dispatch('getActiveState');
      this.$store.commit("SET_TOTLE_DATA", { activationVisible: false });
      Toast({
        message: data.msg || '激活成功',
        position: 'bottom',
      });
    }
  },
};
</script>
<style lang="scss" scoped>
</style>
